package db.springdata;

import db.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class TestStudentRepository2 {
    @Autowired
    StudentRepository2 repository;

    void output(Iterable<Student> students) {
        for (Student s : students) {
            System.out.println(s);
        }
    }

    // 查找年龄小于15的学生
    void listByAge() {
        List<Student> students = repository.findByAgeLessThan(15);
        output(students);
    }

    // 查找出生日期范围的学生
    void listBirthdayBetween() throws ParseException {
        // 用两种方法获取日期对象
        // 1) parse String to date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date b = sdf.parse("2010-01-01");
        // 2) 使用 calendar
        Calendar c = Calendar.getInstance();
        c.set(2015, Calendar.MAY, 1);
        Date e = c.getTime();


    }

    // 按年龄排序
    void listOrderByAge() {

    }

    // 分页、排序
    void listPage(Pageable pageable) {

    }

    public static void main(String[] args) throws ParseException {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig4H2.class);
        TestStudentRepository2 t = ctx.getBean(TestStudentRepository2.class);

        // 查找年龄小于15的学生
        t.listByAge();

        // 查找出生日期范围的学生
        t.listBirthdayBetween();

        // 按年龄排序
        t.listOrderByAge();

        // 仅分页
        Pageable pageable = PageRequest.of(0, 10);
        t.listPage(pageable);

        // 分页+排序
        Sort s = Sort.by(Sort.Order.by("birthday"));
        pageable = PageRequest.of(0, 10, s);
        t.listPage(pageable);
    }
}
